
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>报价单</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi" />
  <link rel="stylesheet" href="${re.contextPath}/plugin/layui/css/layui.css">
  <script type="text/javascript" src="${re.contextPath}/plugin/jquery/jquery-3.2.1.min.js"></script>
  <script type="text/javascript" src="${re.contextPath}/plugin/layui/layui.all.js" charset="utf-8"></script>
  <script type="text/javascript" src="${re.contextPath}/plugin/tools/tool.js"></script>
  <meta charset="utf-8" />
  <meta name="renderer" content="webkit" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <meta name="apple-mobile-web-app-status-bar-style" content="black" />
  <meta name="apple-mobile-web-app-capable" content="yes" />
  <meta name="format-detection" content="telephone=no" />

  <link rel="stylesheet" href="layui/css/layui.css" />
  <!--[if lt IE 9]>
  <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
  <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
  <![endif]-->
  <style type="text/css">
    /*您可以将下列样式写入自己的样式表中*/
    .childBody{padding: 15px;}

    /*layui 元素样式改写*/
    .layui-btn-sm{line-height: normal; font-size: 12.5px;}
    .layui-table-view .layui-table-body{min-height: 256px;}
    .layui-table-cell .layui-input.layui-unselect{height: 30px; line-height: 30px;}

    /*设置 layui 表格中单元格内容溢出可见样式*/
    .table-overlay .layui-table-view,
    .table-overlay .layui-table-box,
    .table-overlay .layui-table-body{overflow: visible;}
    .table-overlay .layui-table-cell{height: auto; overflow: visible;}

    /*文本对齐方式*/
    .text-center{text-align: center;}
  </style>

</head>

<body class="childBody">
<form class="layui-form layui-form-pane" id="saveForm" style="margin-left: 20px;">
  <div class="layui-form-item">
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 10px;">
      <legend style="font-size:16px;">报价单</legend>
    </fieldset>
  </div>
<#--  <div class="layui-input-inline">-->
<#--    <button type="button" class="layui-btn" id="test3"><i class="layui-icon"></i>上传文件</button>-->
<#--  </div>-->
  <div class="layui-form-item">
    <div class="layui-inline">
      <label for="uname" class="layui-form-label">
        <span class="x-red">*</span>报价编号
      </label>
      <div class="layui-input-inline">
        <input type="text" id="orderNo" value="${quotation.orderNo}"  name="orderNo" lay-verify="orderNo"  autocomplete="off" class="layui-input">
        <input type="hidden" id="id" value="${quotation.id}"  name="id" lay-verify="orderNo"  autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-inline">
      <label for="noticeTime" class="layui-form-label">
        <span class="x-red">*</span>日期
      </label>
      <div class="layui-input-inline">
        <div class="layui-input-inline">
          <input type="text"  id="addTime" name="addTime" value="${(quotation.addTime?string('yyyy-MM-dd hh:mm:ss'))!}"   placeholder="yyyy-MM-dd HH:mm:ss"
                 autocomplete="off" class="layui-input">
        </div>
      </div>
    </div>
    <div class="layui-inline">
      <label for="saleName" class="layui-form-label">
        <span class="x-red">*</span>销售
      </label>
      <div class="layui-input-inline">
        <input type="text" id="saleName" value="${quotation.saleName}" name="saleName" lay-verify="saleName"  autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-inline">
      <label for="salePhone" class="layui-form-label">
        <span class="x-red">*</span>销售电话
      </label>
      <div class="layui-input-inline">
        <input type="text" id="salePhone" value="${quotation.salePhone}" name="salePhone"  lay-verify="salePhone"
               autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-inline">
      <label for="company" class="layui-form-label">
        <span class="x-red">*</span>公司
      </label>
      <div class="layui-input-inline">
        <input type="text"  id="company" value="${quotation.company}" name="company"  lay-verify="company"
               autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-inline">
      <label for="conpanyAdress" class="layui-form-label">
        <span class="x-red">*</span>公司地址
      </label>
      <div class="layui-input-inline">
        <input type="text" id="conpanyAdress" value="${quotation.conpanyAdress}"  name="conpanyAdress" lay-verify="conpanyAdress"  autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-inline">
      <label for="companyContact" class="layui-form-label">
        <span class="x-red">*</span>联系人
      </label>
      <div class="layui-input-inline">
        <input type="text" id="companyContact" value="${quotation.companyContact}" name="companyContact"  lay-verify="companyContact"
               autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-inline">
      <label for="companyPhone" class="layui-form-label">
        <span class="x-red">*</span>联系电话
      </label>
      <div class="layui-input-inline">
        <input type="text"  id="companyPhone" value="${quotation.companyPhone}" name="companyPhone"  lay-verify="companyPhone"
               autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <div class="layui-inline">
      <label for="deliveryDate" class="layui-form-label">
        <span class="x-red">*</span>交期
      </label>
      <div class="layui-input-inline">
        <input type="text" id="deliveryDate" value="${(quotation.deliveryDate?string('yyyy-MM-dd HH:mm:ss'))!}" name="deliveryDate" lay-verify="deliveryDate"  autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-inline">
      <label for="amount" class="layui-form-label">
        <span class="x-red"></span>总金额
      </label>
      <div class="layui-input-inline">
        <input type="text" id="amount" value="${quotation.amount}" name="amount"  lay-verify="amount"
               autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-inline">
      <label for="state" class="layui-form-label">
        <span class="x-red"></span>状态
      </label>
      <div class="layui-input-inline">
        <input type="text"  id="state" value="${quotation.state}" name="state"  lay-verify="state"
               autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>

  <div class="layui-form-item">
    <label for="realName" class="layui-form-label" style="font: 20px;background-color: slategrey;width: 100%">
      <span class="x-red" style="font: 20px">*</span>设计
    </label>
  </div>
  <section class="layui-col-md10" style="margin: 0 auto; float: none;">
    <div class="layui-card">
      <div class="layui-card-body layui-text">
        <div id="tableRes2" class="table-overlay">
          <table id="designTable" lay-filter="dataTable" class="layui-hide"></table>
        </div>
      </div>
    </div>

  </section>

  <div class="layui-form-item">

    <div class="layui-inline">
      <label for="L_repass" class="layui-form-label">
        <span class="x-red"></span>税点
      </label>
      <div class="layui-input-inline">
        <input type="text" id="tax" name="tax" value="${quotation.tax}" lay-verify="amount"
               autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-inline">
      <label for="L_repass" class="layui-form-label">
        <span class="x-red"></span>邮费
      </label>
      <div class="layui-input-inline">
        <input type="text" id="postage" name="postage" value="${quotation.postage}" lay-verify="amount"
               autocomplete="off" class="layui-input">
      </div>
    </div>

    <div class="layui-inline">
      <label for="L_repass" class="layui-form-label">
        <span class="x-red"></span>总金额
      </label>
      <div class="layui-input-inline">
        <input type="text" id="totalMoney" name="totalMoney" value="${quotation.totalMoney}" lay-verify="amount"
               autocomplete="off" class="layui-input">
      </div>
    </div>

    <div class="layui-inline">
      <label for="age" class="layui-form-label">
        <span class="x-red"></span>文件
      </label>
      <div class="layui-input-inline">
        <div class="layui-input-inline">
          <input type="text"  id="file" name="file" onclick="danji()" value="${quotation.file}" lay-verify="file"
                 autocomplete="off" class="layui-input">
        </div>
      </div>
    </div>
  </div>
  <#if !detail>
    <section class="layui-col-md10" style="margin: 0 auto; float: none;">
      <div class="layui-card">
        <div class="layui-card-body layui-text">
          <div id="tableRes" class="table-overlay">
            <table id="dataTable" lay-filter="dataTable" class="layui-hide"></table>
          </div>
          <div id="action" class="text-center">
            <button type="button" name="btnSave" class="layui-btn" data-type="save"><i class="layui-icon layui-icon-ok-circle"></i>保存</button>
            <button  class="layui-btn"  lay-filter="trans" lay-submit >
              生成通知单
            </button>
            <button  class="layui-btn"  lay-filter="down" lay-submit >
              下载
            </button>
            <button type="reset" name="btnReset" class="layui-btn layui-btn-primary">取消</button>
          </div>
        </div>
      </div>

    </section>
  </#if>
</form>
<script type="text/javascript">
  //准备视图对象
  window.viewObj = {
    tbData: [{
      sample: '1',
      design: '1',
      material: '1',
      technology: '1',
      handle: '1',
      number: '1'

    }],
    typeData: [
      {id: 1, name: '分类一'},
      {id: 2, name: '分类二'},
      {id: 3, name: '分类三'},
      {id: 4, name: '分类四'}
    ],
    renderSelectOptions: function(data, settings){
      settings =  settings || {};
      var valueField = settings.valueField || 'value',
              textField = settings.textField || 'text',
              selectedValue = settings.selectedValue || "";
      var html = [];
      for(var i=0, item; i < data.length; i++){
        item = data[i];
        html.push('<option value="');
        html.push(item[valueField]);
        html.push('"');
        if(selectedValue && item[valueField] == selectedValue ){
          html.push(' selected="selected"');
        }
        html.push('>');
        html.push(item[textField]);
        html.push('</option>');
      }
      return html.join('');
    }
  };
  Date.prototype.Format = function (fmt) {
    var o = {
      "M+": this.getMonth() + 1, //月份
      "d+": this.getDate(), //日
      "h+": this.getHours(), //小时
      "m+": this.getMinutes(), //分
      "s+": this.getSeconds(), //秒
      "q+": Math.floor((this.getMonth() + 3) / 3), //季度
      "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
      if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
  };
  function serializeRemoveNull(serStr){
    return serStr.split("&").filter(str => !str.endsWith("=")).join("&");
  }
  function danji() {
    var photos = $("#file").val();
    // document.write(location.href);
    window.open('/images/'+photos,'','');
  }
  function checkC(){
    var order = $("#orderNo").val();
    if(order ==""){
      alert("编号不能为空");
      return false;
    }
    var addTime = $("#addTime").val();
    if(addTime ==""){
      alert("时间不能为空");
      return false;
    }
    var saleName = $("#saleName").val();
    if(saleName ==""){
      alert("销售不能为空");
      return false;
    }

    var company = $("#company").val();
    if(company ==""){
      alert("公司不能为空");
      return false;
    }

    var conpanyAdress = $("#conpanyAdress").val();
    if(conpanyAdress ==""){
      alert("公司地址不能为空");
      return false;
    }

    var companyContact = $("#companyContact").val();
    if(companyContact ==""){
      alert("公司联系人地址不能为空");
      return false;
    }
    var companyPhone = $("#companyPhone").val();
    if(companyPhone ==""){
      alert("公司联系电话地址不能为空");
      return false;
    }
    var deliveryDate = $("#deliveryDate").val();
    if(deliveryDate ==""){
      alert("交期不能为空");
      return false;
    }
    return true;
  }
  function sub() {
    var dataFrom = serializeRemoveNull($("#saveForm").serialize());
    var tableData= JSON.stringify(table.cache[layTableId]);
    console.log(addTime);
    $.ajax({
      url: "addDemand",
      type: "post",
      data:JSON.parse(dataFrom),
      success: function (data) {
        window.top.layer.msg("保存成功", {icon: 6, offset: 'rb', area: ['120px', '80px'], anim: 2});
        window.parent.location.reload();//刷新父页面
        var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
        parent.layer.close(index);
      },
      error: function () {
        alert("保存失败");
      }
    })
  }
  function serializeToObject(jsonArray){
    var o = {};
    $.each(jsonArray, function() {
      if (o[this.name] !== undefined) {
        if(o[this.name] !== 'LAY_TABLE_INDEX') {
          if (!o[this.name].push) {
            o[this.name] = [o[this.name]];
          }
          o[this.name].push(this.value || '');
        }
      } else {
        o[this.name] = this.value || '';
      }
      // delete o.LAY_TABLE_INDEX;
    });
    return o;
  }

  //layui 模块化引用
  layui.use(['jquery', 'table','upload', 'layer','form','laydate'], function(){
    var $ = layui.$, table = layui.table, upload = layui.upload,form = layui.form, laydate = layui.laydate, layer = layui.layer;

    //数据表格实例化
    var tbWidth = $("#tableRes").width();
    var order = $('#orderNo').val();
    var layTableId = "layTable";
    var tableIns = table.render({
      elem: '#designTable',
      id: layTableId,
      data: viewObj.tbData,
      width: tbWidth,
      url : 'showProductQuotation?id='+order,
      page: true,
      loading: false,
      even: false, //不开启隔行背景
      cols: [[
        // {title: '序号', type: 'numbers'},
        {field: 'sample', title: '样件名称', edit: 'text'},
        {field: 'design', title: '设计类型', edit: 'text'},
        {field: 'material', title: '材料类型', edit: 'text'},
        {field: 'technology', title: '工艺类型', edit: 'text'},
        {field: 'handle', title: '后处理要求', edit: 'text'},
        {field: 'number', title: '数量', edit: 'text'}
        // {field: 'tempId', title: '操作', templet: function(d){
        //     return '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del" lay-id="'+ d.tempId +'"><i class="layui-icon layui-icon-delete"></i>移除</a>';
        //   }}
      ]],
      done: function(res, curr, count){
        viewObj.tbData = res.data;
      }
    });

    //定义事件集合
    var active = {
      addRow: function(){	//添加一行
        var oldData = table.cache[layTableId];

        var newRow = {id:'1',orderNo:order,sample: '1', design: '1', material: '1', technology: '1',handle: '1',number: '1'};
        oldData.push(newRow);
        console.log(oldData);
        tableIns.reload('dataTable',{
          data : oldData
        });
      },
      updateRow: function(obj){
        var oldData = table.cache[layTableId];
        console.log(oldData);
        for(var i=0, row; i < oldData.length; i++){
          row = oldData[i];
          if(row.tempId == obj.tempId){
            $.extend(oldData[i], obj);
            return;
          }
        }
        tableIns.reload({
          data : oldData
        });
      },
      removeEmptyTableCache: function(){
        var oldData = table.cache[layTableId];
        for(var i=0, row; i < oldData.length; i++){
          row = oldData[i];
          if(!row || !row.tempId){
            oldData.splice(i, 1);    //删除一项
          }
          continue;
        }
        tableIns.reload({
          data : oldData
        });
      },
      save: function(){
        if(checkC() == false){
          return;
        }
        var dataFrom = $("#saveForm").serializeArray();
        var jjj = serializeToObject(dataFrom);

        var taskDetails= JSON.stringify(table.cache[layTableId]);
        jjj.taskDetails = taskDetails;

        var eee = JSON.stringify(jjj);
        $.ajax({
          url: "updateQuotation",
          type: "post",
          dataType:'json',
          contentType: "application/json",
          async:false, traditional: true,
          data:eee,
          success: function (data) {
            window.top.layer.msg("保存成功", {icon: 6, offset: 'rb', area: ['120px', '80px'], anim: 2});
            window.parent.location.reload();//刷新父页面
            var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
            parent.layer.close(index);
          },
          error: function () {
            alert("保存失败");
          }
        })
      }
    }
    upload.render({
      elem: '#test3'
      ,url: 'upload'
      ,accept: 'file',
      before: function(obj){
        //预读，不支持ie8
        obj.preview(function(index, file, result){
          $('#demo2').find('img').remove();
          $('#demo2').append('<span class="x-red">已经上传</span>');
        });
      },done: function(res){
        if(!res.flag){
          layer.msg(res.msg,{icon: 5,anim: 6});
        }else{
          console.log(res);
          $("#file").val(res.msg);
          console.info($('#file').val());
        }
      }
    });
    laydate.render({
      elem: '#deliveryDate'
      ,trigger: 'click'
      // ,format: 'yyyy年MM月dd日'
      ,type: 'datetime'
    });
    laydate.render({
      elem: '#addTime'
      ,trigger: 'click'
      // ,format: 'yyyy年MM月dd日'
      ,type: 'datetime'
    });
    var tbWidth = $("#tableRes1").width();
    // var tableIns1 = table.render({
    //   elem: '#designTable',
    //   id: 'printTable',
    //   data: viewObj.tbData,
    //   width: tbWidth,
    //   url : 'showProductQuotation?id='+order,
    //   page: true,
    //   loading: false,
    //   even: false, //不开启隔行背景
    //   cols: [[
    //     // {title: '序号', type: 'numbers'},
    //     {field: 'sample', title: '样件名称', edit: 'text'},
    //     {field: 'material', title: '材料类型', edit: 'text'},
    //     {field: 'technology', title: '工艺类型', edit: 'text'},
    //     {field: 'designType', title: '设计类型', edit: 'text'},
    //     {field: 'number', title: '数量', edit: 'text'},
    //     {field: 'subtotal', title: '小计', edit: 'text'},
    //     // {field: 'handle', title: '后处理要求', edit: 'text'},
    //     // {field: 'number', title: '数量', edit: 'text'}
    //     // {field: 'tempId', title: '操作', templet: function(d){
    //     //     return '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del" lay-id="'+ d.tempId +'"><i class="layui-icon layui-icon-delete"></i>移除</a>';
    //     //   }}
    //   ]],
    //   done: function(res, curr, count){
    //     viewObj.tbData = res.data;
    //   }
    // });
    form.on('submit(trans)', function(data){
      var da = $("#id").val();
      layer.msg(JSON.stringify(data.field));
      $.ajax({
        url:'trans',
        type:'post',
        dataType: "json",
        data:{id:da},
        async:false, traditional: true,
        success:function(d){
          var index = parent.layer.getFrameIndex(window.name);
          if(d.flag){
            parent.layer.close(index);
            window.parent.layui.table.reload('leaveList');
            window.top.layer.msg(d.msg,{icon:6,offset: 'rb',area:['120px','80px'],anim:2});
          }else{
            layer.msg(d.msg,{icon:5});
          }
        },error:function(){
          layer.alert("请求失败", {icon: 6},function () {
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
          });
        }
      });
      return false;
    });
    form.on('submit(down)', function (obj) {
      var data = $("#id").val();
      var orderNo = $("#orderNo").val();
      //console.log(obj)
      // 获取XMLHttpRequest
      var xmlResquest = new XMLHttpRequest();
      //  发起请求
      xmlResquest.open("POST", "download?id="+data, true);
      // 设置请求头类型
      xmlResquest.setRequestHeader("Content-type", "application/json");
      // xmlResquest.setRequestHeader("id",data.id);
      xmlResquest.responseType = "blob";
      //  返回
      xmlResquest.onload = function(oEvent) {
        //alert(this.status);
        var content = xmlResquest.response;
        // 组装a标签
        var elink = document.createElement("a");

        //获取文件格式,截取文件后缀
        // var fileaddr = data.fileAddress;
        // var index = fileaddr.lastIndexOf(".");
        // var length  =fileaddr.length;
        // var laterName = fileaddr.substring(index,length);
        //拼接下载的文件名
        // var newFileName = data.fileName+laterName;
        var newFileName = orderNo+'报价单.xls';
        //设置文件下载路径
        elink.download = newFileName;
        elink.style.display = "none";
        var blob = new Blob([content]);

        //解决下载不存在文件的问题，根据blob大小判断
        if(blob.size==0){
          layer.msg('服务器没找到此文件，请联系管理员!');
        }else{
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          document.body.removeChild(elink);
        }
      };
      xmlResquest.send();
    });
    //激活事件
    var activeByType = function (type, arg) {
      if(arguments.length === 2){
        active[type] ? active[type].call(this, arg) : '';
      }else{
        active[type] ? active[type].call(this) : '';
      }
    }

    //注册按钮事件
    $('.layui-btn[data-type]').on('click', function () {
      var type = $(this).data('type');
      activeByType(type);
    });

    //监听select下拉选中事件
    form.on('select(type)', function(data){
      var elem = data.elem; //得到select原始DOM对象
      $(elem).prev("a[lay-event='type']").trigger("click");
    });

    //监听工具条
    table.on('tool(dataTable)', function (obj) {
      var data = obj.data, event = obj.event, tr = obj.tr; //获得当前行 tr 的DOM对象;
      console.log(data);
      switch(event){
        case "type":
          //console.log(data);
          var select = tr.find("select[name='type']");
          if(select){
            var selectedVal = select.val();
            if(!selectedVal){
              layer.tips("请选择一个分类", select.next('.layui-form-select'), { tips: [3, '#FF5722'] }); //吸附提示
            }
            console.log(selectedVal);
            $.extend(obj.data, {'type': selectedVal});
            activeByType('updateRow', obj.data);	//更新行记录对象
          }
          break;
        case "state":
          var stateVal = tr.find("input[name='state']").prop('checked') ? 1 : 0;
          $.extend(obj.data, {'state': stateVal})
          activeByType('updateRow', obj.data);	//更新行记录对象
          break;
        case "del":
          layer.confirm('真的删除行么？', function(index){
            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
            layer.close(index);
            activeByType('removeEmptyTableCache');
          });
          break;
      }
    });
  });
</script>
</body>

</html>
